{"componentChunkName":"component---src-templates-post-jsx","path":"/[BOJ]1260/","result":{"data":{"site":{"siteMetadata":{"title":"SUbbb"}},"markdownRemark":{"id":"0c712680-130f-5fa5-8c3b-3632dd5d1af0","excerpt":"문제 그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다. 입력 첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M …","html":"<h2>문제</h2>\n<p>그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다.</p>\n<h3>입력</h3>\n<ul>\n<li>첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.</li>\n</ul>\n<h3>출력</h3>\n<ul>\n<li>첫째 줄에 DFS를 수행한 결과를, 그 다음 줄에는 BFS를 수행한 결과를 출력한다. V부터 방문된 점을 순서대로 출력하면 된다.</li>\n</ul>\n<h3>📍 <strong>Logic</strong></h3>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">class Graph {\n\tpublic ArrayList&lt;ArrayList&lt;Integer&gt;&gt; graph;\n    public boolean[] visited = new boolean[1001];\n    public StringBuilder path = new StringBuilder();\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>graph를 저장하기 위한 동적 2차원 배열</li>\n<li>정점에 대한 방문 여부 저장을 위한 <code class=\"language-text\">boolean</code> 배열</li>\n<li><code class=\"language-text\">DFS</code> 와 <code class=\"language-text\">BFS</code> 의 방문 순서를 저장하는 <code class=\"language-text\">stringBuilder</code></li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public void dfs(int start) {\n\tif (!visited[start]) {\n\t\tpath.append(start);\n\t\tpath.append(&quot; &quot;);\n\t\tvisited[start] = true;\n\t\tfor (int i = 0; i &lt; graph.get(start).size(); i++) {\n\t\t\tif (!visited[graph.get(start).get(i)]) {\n\t\t\t\tthis.dfs(graph.get(start).get(i));\n\t\t\t}\n\t\t}\n\t}\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>재귀 호출을 이용한 DFS 구현</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public void bfs(int start) {\n\tQueue&lt;Integer&gt; q = new LinkedList&lt;&gt;();\n\tq.offer(start);\n\tvisited[start] = true;\n\tpath.append(&quot;\\n&quot;);\n\tpath.append(start);\n\twhile (!q.isEmpty()) {\n\t\tint cur = q.poll();\n\t\tfor (int i = 0; i &lt; graph.get(cur).size(); i++) {\n\t\t\tif (!visited[graph.get(cur).get(i)]) {\n\t\t\t\tvisited[graph.get(cur).get(i)] = true;\n\t\t\t\tpath.append(&quot; &quot;);\n\t\t\t\tpath.append(graph.get(cur).get(i));\n\t\t\t\tq.offer(graph.get(cur).get(i));\n\t\t\t}\n\t\t}\n\t}\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>Queue를 이용한 BFS 구현</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">for (int i = 1; i &lt;= n; i++) {\n\tCollections.sort(g.graph.get(i));\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>번호가 낮은 정점부터 방문하라는 문제의 조건을 위한 정렬</li>\n</ul>\n<h3>📄 <strong>CODE</strong></h3>\n<details>\n  <summary>코드 보기/접기💫</summary>\n    <div markdown=\"1\">\n<deckgo-highlight-code  terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">import java.util.*;\n\nclass Graph {\n\tpublic ArrayList&lt;ArrayList&lt;Integer&gt;&gt; graph;\n\tpublic boolean[] visited = new boolean[1001];\n\tpublic StringBuilder path = new StringBuilder();\n\n\tpublic Graph(int size) {\n\t\tthis.graph = new ArrayList&lt;ArrayList&lt;Integer&gt;&gt;();\n\n\t\tfor (int i = 0; i &lt; size + 1; i++) {\n\t\t\tgraph.add(new ArrayList&lt;Integer&gt;());\n\t\t}\n\t}\n\n\tpublic void DoubleAdd(int x, int y) {\n\t\tgraph.get(x).add(y);\n\t\tgraph.get(y).add(x);\n\t}\n\n\tpublic void dfs(int start) {\n\t\tif (!visited[start]) {\n\t\t\tpath.append(start);\n\t\t\tpath.append(&quot; &quot;);\n\t\t\tvisited[start] = true;\n\t\t\tfor (int i = 0; i &lt; graph.get(start).size(); i++) {\n\t\t\t\tif (!visited[graph.get(start).get(i)]) {\n\t\t\t\t\tthis.dfs(graph.get(start).get(i));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void bfs(int start) {\n\t\tQueue&lt;Integer&gt; q = new LinkedList&lt;&gt;();\n\t\tq.offer(start);\n\t\tvisited[start] = true;\n\t\tpath.append(&quot;\\n&quot;);\n\t\tpath.append(start);\n\t\twhile (!q.isEmpty()) {\n\t\t\tint cur = q.poll();\n\t\t\tfor (int i = 0; i &lt; graph.get(cur).size(); i++) {\n\t\t\t\tif (!visited[graph.get(cur).get(i)]) {\n\t\t\t\t\tvisited[graph.get(cur).get(i)] = true;\n\t\t\t\t\tpath.append(&quot; &quot;);\n\t\t\t\t\tpath.append(graph.get(cur).get(i));\n\t\t\t\t\tq.offer(graph.get(cur).get(i));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic StringBuilder getPath() {\n\t\treturn path;\n\t}\n}\n\npublic class Main {\n\tpublic static void main(String[] args) {\n\t\tScanner sc = new Scanner(System.in);\n\t\tint n = sc.nextInt();\n\t\tint m = sc.nextInt();\n\t\tint start = sc.nextInt();\n\n\t\tGraph g = new Graph(n);\n\n\t\tfor (int i = 0; i &lt; m; i++) {\n\t\t\tint a = sc.nextInt();\n\t\t\tint b = sc.nextInt();\n\n\t\t\tg.DoubleAdd(a,b);\n\t\t}\n\n\t\tfor (int i = 1; i &lt;= n; i++) {\n\t\t\tCollections.sort(g.graph.get(i));\n\t\t}\n\n\t\tArrays.fill(g.visited,false);\n\t\tg.dfs(start);\n\n\t\tArrays.fill(g.visited,false);\n\t\tg.bfs(start);\n\n\t\tSystem.out.print(g.getPath().toString());\n\n\t\tsc.close();\n\t}\n}</code>\n        </deckgo-highlight-code>\n  \t</div>\n</details>\n<h3>✏️ <strong>Review</strong></h3>\n<ul>\n<li>성공했었다가 실패로 재채점되어 이번 기회에 <code class=\"language-text\">JAVA</code> 로 변환하면서 다시 푼 문제</li>\n<li><code class=\"language-text\">class Graph</code> 와 같이 클래스를 만드는 방식을 이용해 Graph와 관련된 처리들을 최대한 클래스 내부에서 구현하도록 했다.</li>\n<li>\n<p>처음에는 <code class=\"language-text\">int[] path</code> 를 두 번 사용하여 <code class=\"language-text\">DFS</code> 의 결과를 출력하고, <code class=\"language-text\">BFS</code> 의 결과를 출력하는 방식으로 구현했었는데, 다른 방식을 찾아보다가 <code class=\"language-text\">StringBuilder</code> 클래스라는 것을 발견하여 이를 사용해보았다.</p>\n<ul>\n<li><code class=\"language-text\">StringBuilder</code> : 여러 문자열을 붙이는 연산을 수행하는 경우 효율적인 클래스로, 해당 문제에서는 정점의 방문 순서를 순차적으로 저장하기 위해 사용했다.</li>\n</ul>\n</li>\n<li>구현 방식은 틀린 것이 없어보였는데 자꾸 <strong>틀렸습니다</strong> 가 떠서 화가 날 때 즈음 발견한 한 반례로 디버깅을 해보니, 정렬 시 <strong>반복 횟수가 1번</strong> 모자란 것이었다. </li>\n<li>추가로, <code class=\"language-text\">visited</code> 배열을 <code class=\"language-text\">int</code> 로 한 경우와 <code class=\"language-text\">boolean</code> 으로 한 경우 시간과 메모리 차이가 존재했는데, <code class=\"language-text\">boolean</code> 의 메모리가 더 적고 시간이 감소했을거란 예상과는 달리, 메모리가 증가한 것을 확인했다. 아직 이유는 잘 모르겠다 ..</li>\n</ul>\n<h3>📕 출처</h3>\n<p><a href=\"https://www.acmicpc.net/problem/1260\">https://www.acmicpc.net/problem/1260</a></p>","frontmatter":{"title":"👩‍💻 1260. DFS와 BFS","date":"December 29, 2021","update":"December 29, 2021","tags":["그래프이론","그래프탐색","BFS","DFS"],"series":"👩‍💻 BOJ"},"fields":{"slug":"/[BOJ]1260/","readingTime":{"minutes":5.27}}},"seriesList":{"edges":[{"node":{"id":"27733333-3aad-5771-a1a1-27b4de4b4a01","fields":{"slug":"/[BOJ]2225/"},"frontmatter":{"title":"👩‍💻 2225. 합분해"}}},{"node":{"id":"548ba188-2afe-5575-b79f-107c6c65b07d","fields":{"slug":"/[BOJ]1012/"},"frontmatter":{"title":"👩‍💻 1012. 유기농 배추"}}},{"node":{"id":"0c712680-130f-5fa5-8c3b-3632dd5d1af0","fields":{"slug":"/[BOJ]1260/"},"frontmatter":{"title":"👩‍💻 1260. DFS와 BFS"}}},{"node":{"id":"0e07a592-06ce-5e01-b5e1-95398330372e","fields":{"slug":"/[BOJ]1707/"},"frontmatter":{"title":"👩‍💻 1707. 이분그래프"}}},{"node":{"id":"df12bfec-ed5c-5fc4-8442-0a4b3f9759a3","fields":{"slug":"/[BOJ]2668/"},"frontmatter":{"title":"👩‍💻 2668. 숫자 고르기"}}},{"node":{"id":"01bbb6dc-812c-5223-87c5-53bf04c0d0a6","fields":{"slug":"/[BOJ]9466/"},"frontmatter":{"title":"👩‍💻 9466. 텀 프로젝트"}}},{"node":{"id":"abc306b3-c3a6-552a-8979-e82d506b3921","fields":{"slug":"/[BOJ]2146/"},"frontmatter":{"title":"👩‍💻 2146. 다리 만들기"}}},{"node":{"id":"b3394e53-5e9a-595e-8da4-bb3debd220c0","fields":{"slug":"/[BOJ]5014/"},"frontmatter":{"title":"👩‍💻 5014. 스타트 링크"}}},{"node":{"id":"be297703-e778-5727-8019-6954bc95da3a","fields":{"slug":"/[BOJ]11559/"},"frontmatter":{"title":"👩‍💻 11559. Puyo Puyo"}}},{"node":{"id":"ddf11545-d468-5269-94b1-5daa2720e886","fields":{"slug":"/[BOJ]17471/"},"frontmatter":{"title":"👩‍💻 17471. 게리맨더링"}}},{"node":{"id":"8d77114d-fc6e-5de2-a3ca-c3b250425a56","fields":{"slug":"/[BOJ]2437/"},"frontmatter":{"title":"👩‍💻 2437. 저울"}}},{"node":{"id":"9a8942ce-552f-51ae-b304-0d0fab8f2eba","fields":{"slug":"/[BOJ]14891/"},"frontmatter":{"title":"👩‍💻 14891. 톱니바퀴"}}},{"node":{"id":"f1c04e8a-df0a-5294-949f-5f3a483cbcb0","fields":{"slug":"/[BOJ]14503/"},"frontmatter":{"title":"👩‍💻 14503. 로봇 청소기"}}},{"node":{"id":"883b6ecf-7528-5c16-92fa-edf12a64e80e","fields":{"slug":"/[BOJ]3190/"},"frontmatter":{"title":"👩‍💻 3190. 뱀"}}},{"node":{"id":"099b2576-7d05-5872-a9f0-f1ee6efd3a9a","fields":{"slug":"/[BOJ]14502/"},"frontmatter":{"title":"👩‍💻 14502. 연구소"}}},{"node":{"id":"50eef059-4e55-5f14-a9cf-fb01b6506f02","fields":{"slug":"/[BOJ]17779/"},"frontmatter":{"title":"👩‍💻 17779. 게리맨더링 2"}}},{"node":{"id":"aa67d90b-4801-574c-b225-56c23737a5e2","fields":{"slug":"/[BOJ]2579/"},"frontmatter":{"title":"👩‍💻 2579. 계단 오르기"}}},{"node":{"id":"9db6b43b-963a-5ebd-b72b-69936cf37858","fields":{"slug":"/[BOJ]14499/"},"frontmatter":{"title":"👩‍💻 14499. 주사위 굴리기"}}},{"node":{"id":"6a79cddd-dc1b-5e34-8a84-af313c37de0e","fields":{"slug":"/[BOJ]15685/"},"frontmatter":{"title":"👩‍💻 15685. 드래곤 커브"}}},{"node":{"id":"5e001d34-d985-545b-83ec-7f1c7caea286","fields":{"slug":"/[BOJ]17144/"},"frontmatter":{"title":"👩‍💻 17144. 미세먼지 안녕!"}}},{"node":{"id":"1d132410-9377-5e55-85b9-4664ff64de73","fields":{"slug":"/[BOJ]9935/"},"frontmatter":{"title":"👩‍💻 9935. 문자열 폭발"}}},{"node":{"id":"e13ff8d6-9b02-56c0-83e2-1d3144f70e1d","fields":{"slug":"/[BOJ]16472/"},"frontmatter":{"title":"👩‍💻 16472. 고냥이"}}},{"node":{"id":"0f782160-aaa9-5c54-80c0-72a15172dd16","fields":{"slug":"/[BOJ]1083/"},"frontmatter":{"title":"👩‍💻 1083. 소트"}}},{"node":{"id":"fef58615-9e18-5f50-8d09-3d1e2839342f","fields":{"slug":"/[BOJ]20922/"},"frontmatter":{"title":"👩‍💻 20922. 겹치는 건 싫어"}}},{"node":{"id":"7ca89240-c65f-5cb4-aeef-c5f1605ebd00","fields":{"slug":"/[BOJ]16172/"},"frontmatter":{"title":"👩‍💻 16172. 나는 친구가 적다(Large)"}}}]},"previous":{"fields":{"slug":"/[Algorithm]graph/"},"frontmatter":{"title":"💡 Graph 이론"}},"next":{"fields":{"slug":"/[스프링입문]1/"},"frontmatter":{"title":"📺 1. 프로젝트 환경설정"}}},"pageContext":{"id":"0c712680-130f-5fa5-8c3b-3632dd5d1af0","series":"👩‍💻 BOJ","previousPostId":"b0e662c4-8dab-58b1-8e34-76fd1f26ad52","nextPostId":"dff670de-9a25-5abe-9b4f-84af280c0807"}},"staticQueryHashes":[]}